// cloudfunctions/user-center/index.js
const uniIdCommon = require('uni-id-common')
module.exports = {
  main: async (event, context) => {
    const uniId = uniIdCommon.createInstance({ context })
	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}
    const db = uniCloud.database()
    
    try {
      // 添加参数校验
      if (!body.uniIdToken) {
        return { code: 401, message: '缺少token参数' }
      }

      const payload = await uniId.checkToken(body.uniIdToken)
      
      if (payload.code) {
        return {
          code: payload.code,
          message: 'Token验证失败: ' + payload.message,
          data: null
        }
      }

      // 添加数据库查询获取最新数据
      const userRecord = await db.collection('uni-id-users')
        .doc(payload.uid)
        .field({ test_frequency:1 }) // 只返回必要字段
        .get()

      return {
        code: 0,
        message: 'success',
        data: {
          uid: payload.uid,
          userInfo: {
            ...payload.userInfo,
            test_frequency: userRecord.data[0].test_frequency || 0
          }
        }
      }
      
    } catch (error) {
      console.error('云函数错误:', error)
      return {
        code: -1,
        message: '服务器错误: ' + error.message,
        data: null
      }
    }
  }
}